package com.huadao.cart_ccs.experiment.test;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseDialogFragment;
import com.huadao.cart_ccs.base.BasePresenter;
import com.huadao.cart_ccs.common.ByteUtils;
import com.huadao.cart_ccs.common.adapter.CommonRecycleAdapter;
import com.huadao.cart_ccs.common.adapter.CommonViewHolder;
import com.huadao.cart_ccs.common.adapter.FooterHolder;
import com.huadao.cart_ccs.common.adapter.HeaderHolder;
import com.huadao.cart_ccs.common.dialog.DialogFragmentHelper;
import com.huadao.cart_ccs.data.bo.BaseBO;
import com.huadao.cart_ccs.data.source.serialport.SerialPortSource;

import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 仅用于测试
 */
public class ForceTestDF extends BaseDialogFragment implements ForceTestContract.IForceTestView {

    @BindView(R.id.spinner_operate)
    Spinner spinnerOperate;
    @BindView(R.id.et_times)
    EditText etTimes;
    @BindView(R.id.rv_result)
    RecyclerView rvResult;
    private ForceTestAdapte adapte;
    @BindView(R.id.tv_exception_data)
    TextView tv_exception_data;
    @BindView(R.id.et_target_data)
    TextView et_target_data;
    @BindView(R.id.et_error)
    EditText et_error;
    @BindView(R.id.btn_result)
    Button btn_result;
    @BindView(R.id.btn_stop)
    Button btn_stop;
    @BindView(R.id.et_gap_times)
    EditText et_gap_times;

    private ForceTestPresenter presenter;
    private long originGap=SerialPortSource.minSendTimeGap;

    @Override
    protected BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialogfrag_forcetest;
    }

    @Override
    protected void onInit() {
        et_gap_times.setText(String.valueOf(SerialPortSource.minSendTimeGap));
        presenter = new ForceTestPresenter(this);
        adapte = new ForceTestAdapte(getActivity(), presenter.getResultList(), R.layout.item_test_result);
        rvResult.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvResult.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        rvResult.setAdapter(adapte);
        rvResult.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftInput(v);
                return false;
            }
        });
    }

    @Override
    public double getError() {
        if (TextUtils.isEmpty(et_error.getText())) {
            return -1;
        }
        return Double.parseDouble(et_error.getText().toString());
    }

    @Override
    public void onAddResult(int index) {
        adapte.notifyItemInserted(index);
    }

    @Override
    public void onFinish() {
        DialogFragmentHelper.showMessageDialog(getActivity(),null,"测试完成，请查看统计结果！");
    }

    @Override
    public void notifyList() {
        adapte.notifyDataSetChanged();
    }

    @Override
    public double getTargetDate() {
        if (TextUtils.isEmpty(et_target_data.getText())) {
            return -1;
        }
        return Double.parseDouble(et_target_data.getText().toString());
    }

    @Override
    public int getTimes() {
        if (TextUtils.isEmpty(etTimes.getText())) {
            return -1;
        }
        return Integer.parseInt(etTimes.getText().toString());
    }

    @Override
    public void showExceptionDataCount(int count) {
        tv_exception_data.setText(String.valueOf(count));
    }

    @OnClick({R.id.btn_clear, R.id.btn_start, R.id.btn_result, R.id.choose,R.id.btn_stop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_clear:
                etTimes.setText("");
                et_error.setText("");
                et_target_data.setText("");
                et_gap_times.setText("");
                presenter.clear();
                break;
            case R.id.btn_start:
                String error = checkParams();
                if (error != null) {
                    showToast(error);
                } else {
                    int gap=Integer.parseInt(et_gap_times.getText().toString());
                    SerialPortSource.minSendTimeGap=gap;
                    presenter.operate();
                }
                break;
            case R.id.btn_result:
                String report = generateReport();
                DialogFragmentHelper.showMessageDialog(getActivity(), "统计结果", report);
                break;
//            case R.id.choose:
//                ElectronicScaleBO e=new ElectronicScaleBO();
//                e.setWeight(1000);
//                e.setCommondWord(CommandWord.readSucc[0]);
//                EventBus.getDefault().post(e);
//                break;
            case R.id.btn_stop:
                presenter.stop();
                break;
        }
    }

    @Override
    public int getOperate() {
        return spinnerOperate.getSelectedItemPosition();
    }

    @Override
    public void onDestroy() {
        //复原
        SerialPortSource.minSendTimeGap=originGap;
        super.onDestroy();
    }

    private String generateReport() {
        StringBuilder stringBuilder = new StringBuilder();
        Map<Double, Integer> res = presenter.getStaticsResult();
        if (res == null || res.size() == 0) {
            stringBuilder.append("没有统计结果");
            return stringBuilder.toString();
        }
        Set<Double> keySet = res.keySet();
        if (keySet == null || keySet.size() == 0) {
            stringBuilder.append("没有统计结果");
            return stringBuilder.toString();
        }

        for (Double key : keySet) {
            if (key != -1d) {
                if(getOperate()!=0&&getOperate()!=1){
                    stringBuilder.append("成功  ");
                }else {
                    stringBuilder.append(String.valueOf(key));
                    stringBuilder.append("  ");
                }
            } else {
                stringBuilder.append("失败  ");
            }
            stringBuilder.append(String.valueOf(res.get(key)));
            stringBuilder.append("次\n");
        }
        return stringBuilder.toString();
    }

    private String checkParams() {
        String eror = null;
        if (TextUtils.isEmpty(etTimes.getText())) {
            eror = "请输入次数";
        } else if (TextUtils.isEmpty(et_target_data.getText())) {
            eror = "请输入比较数据";
        } else if (TextUtils.isEmpty(et_error.getText())) {
            eror = "请输入误差";
        }else if(TextUtils.isEmpty(et_gap_times.getText())){
            eror = "请输入间隔";
        }
        return eror;
    }

    class ForceTestAdapte extends CommonRecycleAdapter<BaseBO> {

        public ForceTestAdapte(Context context, List<BaseBO> dataList, int layoutId) {
            super(context, dataList, layoutId);
        }

        @Override
        protected void bindData(CommonViewHolder holder, BaseBO data) {

        }

        @Override
        public void onBindViewHolder(@NonNull CommonViewHolder holder, int position) {
            BaseBO baseBO=dataList.get(position);
            holder.setText(R.id.tv_count, String.valueOf(position+1));
            holder.setText(R.id.tv_msg, baseBO.toString());
            holder.setText(R.id.tv_bytes,ByteUtils.getHexByte(baseBO.getProtocol(),0,baseBO.getProtocol().length));
        }

        @Override
        protected void bindFooterData(FooterHolder holder) {

        }

        @Override
        protected void bindHeaderData(HeaderHolder holder) {

        }
    }

}
